<template>
  <div class="guideScreen-page">
    <breadcrumb />
    <div class="search-container">
      <Search :listData="listData" @search="getSearchParams" />
    </div>
    <div class="table-container">
      <div class="table-component">
        <Buttons @buttons="getButtonsParams" />
        <Table :tableData="table.data" :loading="table.loading" @table="getTableParams" />
        <div class="pagination">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="pagination.pageSizes"
            layout="total,sizes, prev, pager, next, jumper"
            :total="table.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
        <el-dialog
          v-model="dialogVisible"
          :title="title"
          destroy-on-close
          :before-close="handleClose"
          :close-on-click-modal="false"
          :width="
            componentTag === statusComponent || componentTag === importComponent
              ? '520px'
              : '1000px'
          "
        >
          <template #header>
            <div
              v-if="componentTag === addComponent || componentTag === editComponent"
              class="row"
            >
              <div>{{ title }}</div>
              <el-tooltip content="仅当设备处于使用中，可进行参数配置" placement="right">
                <img class="icon-tips" :src="tips" alt="" />
              </el-tooltip>
            </div>
          </template>
          <component
            :is="componentTag"
            @operationDone="operationDone"
            :operationId="operationId"
            :listData="listData"
          >
          </component>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, shallowRef } from "vue";
import breadcrumb from "@/components/breadcrumb/index.vue";
import Search from "./components/search.vue";
import Buttons from "./components/buttons.vue";
import Table from "./components/table.vue";
import statusComponent from "./components/statusComponent.vue";
import addComponent from "./components/addComponent.vue";
import editComponent from "./components/editComponent.vue";
import importComponent from "./components/importComponent.vue";
import tips from "@/assets/image/tips2.png";

import { getGuideList, getDeleteGuide, getExportGuide } from "./request.js";
import { getDictionary, getVendorList } from "@/service/modules/publicModule";

// 弹窗
const title = ref("");
const dialogVisible = ref(false);
const componentTag = shallowRef("");
const operationId = ref("");
const operationDone = (r) => {
  dialogVisible.value = false;
  operationId.value = "";
  if (!r) {
    getData();
  }
};

// 搜索
const searchModel = ref({
  name: "",
  vendor: "",
  status: 1,
  runStatus: "",
});

// 搜索操作
const getSearchParams = (value) => {
  // searchParams.value = value;
  searchModel.value = value;
  getData();
};

// buttons按钮
const getButtonsParams = (value) => {
  console.log("value ===>", value);
  if (value === 1) {
    title.value = "新增诱导屏信息";
    componentTag.value = addComponent;
  } else if (value === 2) {
    if (guideIdList.value.length === 0) {
      ElMessage.error("请选择设备信息");
      return;
    }
    title.value = "修改使用状态";
    componentTag.value = statusComponent;
    operationId.value = guideIdList.value;
  } else if (value === 3) {
    title.value = "导入地磁信息";
    componentTag.value = importComponent;
  } else if (value === 4) {
    exportData();
    return;
  }
  dialogVisible.value = true;
};

const guideIdList = ref([]);

// table操作
const getTableParams = (value) => {
  console.log("value ===>", value);
  if (value.operation === 1) {
    title.value = "编辑诱导屏信息";
    componentTag.value = editComponent;
  } else if (value.operation === 2) {
    deleteData(value);
    return;
  } else if (value.operation === 3) {
    guideIdList.value = value.guideIdList;
    return;
  }
  operationId.value = value;
  dialogVisible.value = true;
};

const deleteData = (row) => {
  ElMessageBox.confirm(`您确认要删除诱导屏[${row.vendorId}]？`, "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await getDeleteGuide(row.id).then((res) => {
      if (res.data.code === 0) {
        getData();
        ElMessage({
          type: "success",
          message: `已删除诱导屏[${row.vendorId}]`,
        });
      } else {
        ElMessage.error(res.data.msg);
      }
    });
  });
};

const exportData = () => {
  ElMessageBox.confirm(`您确认要导出数据？`, "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await getExportGuide({
      vendor: searchModel.value.vendor,
      status: searchModel.value.status,
      runStatus: searchModel.value.runStatus,
    })
      .then((res) => {
        console.log("res ===>", res);
        const fileName = extractFileNameFromHeaders(res.headers);
        const url = window.URL.createObjectURL(new Blob([res.data]));
        const link = document.createElement("a");
        link.href = url;
        link.download = fileName;
        link.click();
      })
      .catch((err) => {
        console.log("err ===>", err);
      });
  });
};

function extractFileNameFromHeaders(headers) {
  const contentDisposition = headers.get("content-disposition") || "";

  const matches = contentDisposition.match(/filename\*=\s*utf-8''([^;]+)/);

  if (matches != null && matches[1]) {
    return decodeURIComponent(matches[1].replace('"', ""));
  }
  return "unknown-file.pdf"; // 默认文件名
}

// 表格
const table = reactive({
  data: [],
  total: 0,
  loading: true,
});

const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  pageSizes: [10, 20, 30, 50],
});

const handleCurrentChange = (value) => {
  pagination.currentPage = value;
  getData();
};

const handleSizeChange = (value) => {
  pagination.pageSize = value;
  getData();
};

const getData = async () => {
  getGuideList({
    name: searchModel.value.name,
    vendor: searchModel.value.vendor,
    status: searchModel.value.status,
    runStatus: searchModel.value.runStatus,
    pageNo: pagination.currentPage,
    pageSize: pagination.pageSize,
  }).then((res) => {
    if (res.data.code === 0) {
      table.data = res.data.result.items;
      table.total = parseInt(res.data.result.total);
      table.loading = false;
    }
  });
};

const listData = reactive({
  vendor: [],
  status: [],
  level: [],
  rp: [],
  netPattern: [],
});

const init = async () => {
  await getVendorList("5").then((res) => {
    listData.vendor = res.data.result;
  });
  await getDictionary("device_use_state").then((res) => {
    listData.status = res.data.result;
  });
  await getDictionary("screen_level").then((res) => {
    listData.level = res.data.result;
  });
  await getDictionary("screen_rp").then((res) => {
    listData.rp = res.data.result;
  });
  await getDictionary("net_model").then((res) => {
    listData.netPattern = res.data.result;
  });
};

getData();
init();
</script>

<style lang="less" scoped>
.guideScreen-page {
  .search-container {
    margin-top: 16px;
    min-height: 100%;
    padding: 24px 24px 8px 24px;
    background: #fff;
    border-radius: 6px;
  }
  .table-container {
    margin-top: 16px;
    min-height: 100%;
    padding: 24px;
    background: #fff;
    border-radius: 6px;
    .table-component {
      .pagination {
        display: flex;
        align-items: center;
        justify-content: flex-end;
      }
    }
  }
  .icon-tips {
    width: 20px;
    height: 20px;
  }
  .row {
    display: flex;
    align-items: center;
  }
}
</style>
